const { Controller } = require('egg');
class BaseController extends Controller {


  wxappid = 'wx81b937195945b472'
  wxsecret = "7cc1cb020a47a94b3a20e25054de498f"

  async get_access_token() {
    const { ctx, ctx: { service, customBody }, app, app: { mysql } } = this;
    var url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${this.wxappid}&secret=${this.wxsecret}`;
    const result = await app.curl(url, {
      contentType: 'json',
    });
    var jsonstring = result.data.toString()
    var jsonobject = JSON.parse(jsonstring)
    return jsonobject.access_token
    // 获取参数然后保存
    // var { openid = 'opHTu0BFAOqiHVyDhcIX3mEesfgk' } = customBody
    // var istrue = await service.user.find(openid)
    // ctx.body = istrue;
    // var userInfo = await mysql.get('wx_user', { openid })
    // ctx.body = userInfo;
  }
  upperJSONKey(jsonObj) {
    for (var key in jsonObj) {
      jsonObj["" + key.toLowerCase() + ""] = jsonObj[key];
    }
    return jsonObj;
  }

  success(data) {
    var res = data.data
    // 格式化时间
    // for (const key of res) {
    //   if (key.create_time) {
    //     key.create_time = parseTime(key.create_time)
    //     key.update_time = parseTime(key.update_time)
    //   }
    // }




    this.ctx.body = {
      ...data
    };
  }

  notFound(msg) {
    msg = msg || 'not found';
    this.ctx.throw(404, msg);
  }
}
module.exports = BaseController;

// 格式化时间
/**
function parseTime(time, cFormat) {
  time = +new Date(time)
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}
*/